﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using OSGeo.GDAL;
using GribFirst;
using Grib2_Decoder;
using NetCDFDotnet;
using HDFDotnet;
using HDF5;

namespace GeoFly
{
	public partial class Form1 : Form
	{
		public HortonHydroSimulate Hydro;
		public double Longitude;
		public Form1()
		{
			InitializeComponent();
			Hydro = new HortonHydroSimulate(this.river);
		}
        

		private void Form1_Paint(object sender, PaintEventArgs e)
		{
			this.mapViewer1.Display();

		}


		public DEMRiverNet river = null;
		public GeoFly.MapCoordConvertor MapCoord = new GeoFly.MapCoordConvertor();
		public int[,] dmatrix = null;
		public ClimateGene WGen = new ClimateGene();

		private void 流向矩阵ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (river.demgrid == null)
				throw new Exception("你还没有载入DEM数据");
            
			MyTreeNode tempNode = (MyTreeNode)this.treeView1.SelectedNode;
			if (tempNode.IsLayer == false) {
				tempNode = (MyTreeNode)tempNode.Parent;
			}
			river.demgrid = tempNode.gridlayer;
            
			dmatrix = river.GridGradientDirection();
			//Common.SaveMatrix(dmatrix, "C:\\direction.asc");
			Bitmap bitmap = MatrixFuncs.BitmapFromMatrix(dmatrix);
			//建立图像节点
			MyTreeNode node = new MyTreeNode();
			node.IsLayer = true;
			node.gridlayer=tempNode.gridlayer.AttributesCopy();
			
			node.gridlayer.Values=MatrixFuncs.Int2Double(dmatrix);
			node.bitmap = bitmap;
			node.Text = "流向矩阵";
			tempNode.Nodes.Add(node);
			this.treeView1.SelectedNode = node;
			mapViewer1.theBitmap = node.bitmap;
			mapViewer1.Display();
		}

		private void 累积流量矩阵ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)this.treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			river.demgrid = tempNode.gridlayer;
			DateTime t1 = DateTime.Now;
			int[,] matrix = river.FlowAccumu_Liu3();
			//Common.SaveMatrix(matrix, "C:\\accum.asc");
			double[,] ma = MatrixFuncs.LogTransform(matrix);
			DateTime t2 = DateTime.Now;
			TimeSpan t = t2 - t1;
			this.Text = t.TotalMilliseconds.ToString();
			Bitmap bitmap = MatrixFuncs.BitmapFromMatrix6(ma); //river.CeateRiverSysImage(matrix, 10);
			MyTreeNode node = new MyTreeNode();
			node.Text = "累积流量矩阵";
			node.bitmap = bitmap;
			node.IsLayer = true;
			node.gridlayer=tempNode.gridlayer.AttributesCopy();
			
			node.gridlayer.Values=MatrixFuncs.Int2Double(matrix);
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = bitmap;
			mapViewer1.Display();
		}

		private void 保存当前位图ToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void 水系矩阵ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)this.treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			river.demgrid = tempNode.gridlayer;
			DateTime t1 = DateTime.Now;
			int[,] matrix = river.FlowAccum_Old(this.dmatrix);
			DateTime t2 = DateTime.Now;
			TimeSpan t = t2 - t1;
			this.Text = t.TotalMilliseconds.ToString();
			//int[,] matrix = river.FlowAccum_Old(this.dmatrix);
			Bitmap bitmap = MatrixFuncs.BitmapFromMatrix5(matrix); //river.CeateRiverSysImage(matrix, 10);
			MyTreeNode node = new MyTreeNode();
			node.Text = "累积流量矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = bitmap;
			mapViewer1.Display();

		}

		private void 计算坡向矩阵ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			double[,] values = river.CalcAspect();
			//GridLayer gridlayer = ((MyTreeNode)this.treeView1.SelectedNode).gridlayer;
			for (int i = 0; i < values.GetLength(0); i++) {
				for (int j = 0; j < values.GetLength(1); j++) {
					values[i, j] = Math.Cos(values[i, j]);
				}
			}
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			MyTreeNode node = new MyTreeNode();
			node.Text = "坡向矩阵";
			node.bitmap = MatrixFuncs.BitmapFromMatrix(values);
			tempNode.Nodes.Add(node);
			this.mapViewer1.theBitmap = node.bitmap;
			this.mapViewer1.Display();
		}

		private void 载入数据ToolStripMenuItem_Click_1(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = "*.asc";
			openFileDialog1.Filter = "Text File(*.txt|*.txt|ASCII码文件(*.asc)|*.asc|All files (*.*)|*.*";
			if (this.openFileDialog1.ShowDialog() == DialogResult.OK) {
				GridLayer gridlayer = new GridLayer();
				string ext = Path.GetExtension(openFileDialog1.FileName);
				if (ext == ".asc" || ext == ".txt")
					gridlayer.ReadASC(openFileDialog1.FileName);
				else if (ext == ".hgt")
					gridlayer.ReadHGT(openFileDialog1.FileName);
               
				Bitmap bitmap = null;
				if (this.comboBox_ColorSetting.SelectedIndex == 0) {
					bitmap = gridlayer.CreateBitmap();
				} else if (this.comboBox_ColorSetting.SelectedIndex == 1) {
					bitmap = gridlayer.CreateBitmap(this.button_2_Color1.BackColor, this.button_2_Color2.BackColor);
				} else if (this.comboBox_ColorSetting.SelectedIndex == 2) {
					bitmap = gridlayer.CreateBitmap(this.button_3_Color1.BackColor, this.button_3_Color2.BackColor, this.button_3_Color3.BackColor);
				} else if (this.comboBox_ColorSetting.SelectedIndex == 3) {
					bitmap = gridlayer.CreateBitmap5();
				} else if (this.comboBox_ColorSetting.SelectedIndex == 4) {
					bitmap = gridlayer.CreateBitmap6();
				}

				river = new DEMRiverNet(gridlayer);
                
				MyTreeNode node = new MyTreeNode();
				node.IsLayer = true;
				node.gridlayer = gridlayer;
				node.Text = node.gridlayer.FileName;
                
				this.treeView1.Nodes.Add(node);
				this.treeView1.SelectedNode = node;
				mapViewer1.theBitmap = bitmap;
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();
				DEM_Menu.Enabled = true;
			}
		}

		private void aewqwrToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void 保存部分数据ToolStripMenuItem_Click_1(object sender, EventArgs e)
		{
			if (this.saveFileDialog1.ShowDialog() == DialogResult.OK) {
				((MyTreeNode)this.treeView1.SelectedNode).gridlayer.WriteASC(saveFileDialog1.FileName, 300, 540, 200, 700);
			}
		}

		private void 保存数据为ASCIIToolStripMenuItem_Click_1(object sender, EventArgs e)
		{
			saveFileDialog1.DefaultExt = "*.asc";
			saveFileDialog1.Filter = "ASCII码文件(*.asc)|*.asc|All files (*.*)|*.*";
			if (this.saveFileDialog1.ShowDialog() == DialogResult.OK) {
				MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
				if (tempNode.IsLayer == false)
					tempNode = (MyTreeNode)tempNode.Parent;
				tempNode.gridlayer.WriteASC(saveFileDialog1.FileName);
			}
		}

		private void 保存当前位图ToolStripMenuItem_Click_1(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode == null)
				return;
			saveFileDialog1.DefaultExt = "jpg";
			saveFileDialog1.AddExtension = true;
			saveFileDialog1.Filter = "Jpeg图像文件(*.jpg)|*.jpg|All files (*.*)|*.*";
			if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
				if (tempNode.IsLayer) {
					tempNode.gridlayer.theBitmap.Save(saveFileDialog1.FileName);
				} else {
					tempNode.bitmap.Save(saveFileDialog1.FileName);
				}
			}
		}

		private void 河流分级ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//求流向矩阵
			int[,] DirectionMatrix = river.GridGradientDirection();
			int[,] AccumulationLayer = river.FlowAccumu_Liu3();
			int[,] River = river.FlowStrahlerOrder(50);

			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			MyTreeNode node = new MyTreeNode();
			node.Text = "河道等级矩阵";
			node.bitmap = MatrixFuncs.BitmapFromMatrix6(River);
			//Common.SaveMatrix(River,"c:/River.asc");
			node.IsLayer = true;
			node.gridlayer=tempNode.gridlayer.AttributesCopy();
			
			node.gridlayer.Values=MatrixFuncs.Int2Double(River);
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = node.bitmap;
            
			this.mapViewer1.Display();
			//this.panel1.Refresh();
		}

		private void sdsdfsdafToolStripMenuItem_Click(object sender, EventArgs e)
		{
           
		}
		
		public List<PointF[]> ReadVector(string filename)
		{
			StreamReader sr = new StreamReader(filename);
			List<PointF[]> result = new List<PointF[]>();
			List<PointF> ps = new List<PointF>();
			while (!sr.EndOfStream) {
				
				string s = sr.ReadLine();
				string[] strs = s.Split(new char[]{ '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
				if (s.Contains("NaN") || strs.Length < 2) {
					if (ps.Count > 1)
						result.Add(ps.ToArray());
					ps = new List<PointF>();					
				} else {
					float x = Convert.ToSingle(strs[1]);
					float y = -Convert.ToSingle(strs[0]);
					ps.Add(new PointF(x, y));
				}
			}
			if (ps.Count > 1)
				result.Add(ps.ToArray());
			sr.Close();		
			return result;
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			this.Longitude = Convert.ToDouble(this.TextBox_Longitude.Text);
			StreamReader sr = new StreamReader(Application.StartupPath + "\\DefaultPath.txt");
			HydroSimulate.path = sr.ReadLine();
			sr.Close();
			this.SetPath(HydroSimulate.path);
			this.mapViewer1.doubleMap = true;
			mapViewer1.VCoast = this.ReadVector("globalmap1.txt");
			mapViewer1.VPoints = new PointF[0];
			mapViewer1.VPolygons = new List<PointF[]>();
			mapViewer1.VCountries = this.ReadVector("countries.txt");
			mapViewer1.VRivers = this.ReadVector("rivers.txt");
			mapViewer1.VChina = this.ReadVector("china2.txt");
			MyTreeNode node = new MyTreeNode();
			node.Text = "Output";
			treeView1.Nodes.Add(node);
			//设置系统参数的存放目录,在\\SysPara目录下
			//string dpath = HydroSimulate.path + "\\SysPara";
			//Hydro.m_GridFile = dpath + "\\GridIO.txt";
			//Hydro.m_BasinFile = dpath + "\\Basin.txt";
			//Hydro.m_ClimateFile = dpath + "\\Climate.txt";
			//Hydro.m_RunParaFile = dpath + "\\RunPara.txt";
			//Hydro.m_InputParaFile = dpath + "\\InputPara.txt";
			//Hydro.m_MuskCoeffFile = dpath + "\\muskingum_coeff.txt";
			//Hydro.m_MidOutFile = dpath + "\\MidGridOut.txt";
			//Hydro.m_WaterYrTypeFile = dpath + "\\WaterYearType.txt";
		}

		private void panel1_Paint(object sender, PaintEventArgs e)
		{
			//if (this.HasImage == true)
			//    this.panel1.CreateGraphics().DrawImage(bitmap, 0, 0);
			
		}

		private void 加载系统运行参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (Directory.Exists(HydroSimulate.path) == false) {
				MessageBox.Show("文件路径" + HydroSimulate.path + "不存在!");
				return;
			}
			Hydro.River = this.river;
			Hydro.LoadSystemParaFile(HydroSimulate.path);
			加载ToolStripMenuItem.Enabled = true;
			气象栅格图层ToolStripMenuItem.Enabled = true;
            
		}

		private void 设置目录ToolStripMenuItem_Click(object sender, EventArgs e)
		{

			FolderBrowserDialog dlg = new FolderBrowserDialog();
			if (dlg.ShowDialog() == DialogResult.OK) {
				HydroSimulate.path = dlg.SelectedPath;
				StreamWriter sw = new StreamWriter(Application.StartupPath + "\\DefaultPath.txt");
				sw.WriteLine(dlg.SelectedPath);
				sw.Close();
				//设置系统参数的存放目录,在\\SysPara目录下
				this.SetPath(HydroSimulate.path);
				//string dpath = HydroSimulate.path + "\\SysPara";
				//Hydro.m_GridFile = dpath + "\\GridIO.txt";
				//Hydro.m_BasinFile = dpath + "\\Basin.txt";
				//Hydro.m_ClimateFile = dpath + "\\Climate.txt";
				//Hydro.m_RunParaFile = dpath + "\\RunPara.txt";
				//Hydro.m_InputParaFile = dpath + "\\InputPara.txt";
				//Hydro.m_MuskCoeffFile = dpath + "\\muskingum_coeff.txt";
				//Hydro.m_MidOutFile = dpath + "\\MidGridOut.txt";
				//Hydro.m_WaterYrTypeFile = dpath + "\\WaterYearType.txt";

				Model_Menu.Enabled = true;
				this.SetDirectory_Button.Enabled = true;
				this.LoadDEM_MenuItem.Enabled = true;
			}

		}

		private void 流域边界参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void 土壤ToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void 气象栅格图层ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Hydro.ReadInGridLayerData();
		}

		private void 加载ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Hydro.ReadInClimateData();
			栅格中间结果输出ToolStripMenuItem.Enabled = true;
		}

		private void 开始模拟ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (HydroSimulate.g_ModelRunPara.RunoffSimuType == RunOffSimuType.STORM_RUNOFF_SIMULATION) {
				if (HydroSimulate.g_ModelRunPara.InfilCurveType == InfilltrationType.INFILTRATION_GREEN_AMPT) {
					this.Hydro.StormRunoffSim_GreenAmpt_Liu();
				} else if (HydroSimulate.g_ModelRunPara.InfilCurveType == InfilltrationType.INFILTRATION_HORTON) {
					Hydro.StormRunoffSim_Horton_Liu();
				}
			} else {
				this.Hydro.LongTermRunoffSimulate();
			}
		}

		private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void 寻找水体ToolStripMenuItem_Click(object sender, EventArgs e)
		{
            
		}

		private void 阴影ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			double[,] data = river.CalcuShade();             
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			MyTreeNode node = new MyTreeNode();
			node.bitmap = MatrixFuncs.BitmapFromMatrix(data);
			node.Text = "光照效果";
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = node.bitmap;
			mapViewer1.Display();
		}

		private void 填洼1ToolStripMenuItem_Click(object sender, EventArgs e)
		{
           
		}

		private void 填洼2ToolStripMenuItem_Click(object sender, EventArgs e)
		{
		}

		private void 填洼4ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			TimeSpan t1 = DateTime.Now.TimeOfDay;
			river.CheckPit_LiuYonghe2();
			//Common.SaveMatrix(river.demgrid.Values,"c:/filledDEM.txt");
			MatrixFuncs.SaveMatrix(river.marks2,"marks2.txt");
			TimeSpan t2 = DateTime.Now.TimeOfDay;
			TimeSpan t3 = t2 - t1;
			this.Text = t3.TotalMilliseconds.ToString();
		}

		private void 填洼5经典ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			TimeSpan t1 = DateTime.Now.TimeOfDay;
			river.CheckPit_Planchon(river.m_pDirection, river.demgrid);
			TimeSpan t2 = DateTime.Now.TimeOfDay;
			TimeSpan t3 = t2 - t1;
			this.Text = t3.TotalMilliseconds.ToString();
		}

		private void 填洼6随机选方向ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			TimeSpan t1 = DateTime.Now.TimeOfDay;
			river.CheckPit_Planchon_Modi(river.m_pDirection, river.demgrid);
			TimeSpan t2 = DateTime.Now.TimeOfDay;
			TimeSpan t3 = t2 - t1;
			this.Text = t3.TotalMilliseconds.ToString();
		}

		private void 载入数据ToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = ".R";
			openFileDialog1.Filter = "降雨量文件(*.R)|*.R|所有文件(*.*)|*.*";
			openFileDialog1.Title = "选择单站点多年降水数据的存储位置";
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				WGen.ReadRainfallData(openFileDialog1.FileName);
			}
            
		}

		private void 模型运行参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RunParaDialog dlg = new RunParaDialog();
			dlg.ShowDialog();
		}

		private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = ".tmx";
			openFileDialog1.Filter = "日最高气温文件(*.tmx)|*.tmx|所有文件(*.*)|*.*";
			openFileDialog1.Title = "选择单站点多年日最高气温数据的存储位置";
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				WGen.ReadMaxTempData(openFileDialog1.FileName);
			}
		}

		private void 载入日平均气温ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = ".ta";
			openFileDialog1.Filter = "日平均气温文件(*.ta)|*.ta|所有文件(*.*)|*.*";
			openFileDialog1.Title = "选择单站点多年日平均气温数据的存储位置";
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				WGen.ReadMeanTempData(openFileDialog1.FileName);
			}
		}

		private void 载入日平均风速ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = ".wv";
			openFileDialog1.Filter = "日平均风速文件(*.wv)|*.wv|所有文件(*.*)|*.*";
			openFileDialog1.Title = "选择单站点多年日平均风速数据的存储位置";
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				WGen.ReadWindSpeed(openFileDialog1.FileName);
			}
		}

		private void 载入日平均相对湿度ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.DefaultExt = ".ua";
			openFileDialog1.Filter = "日平均风速文件(*.ua)|*.ua|所有文件(*.*)|*.*";
			openFileDialog1.Title = "选择单站点多年日平均相对湿度数据的存储位置";
			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				WGen.ReadRelaHumid(openFileDialog1.FileName);
			}
		}

		private void 计算日平均露点温度ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			WGen.PrepareAllDewPoint();
		}

		private void 计算ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			WGen.CalcMonthStat();
		}

		private void 生成逐日降水资料ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			double[,] Precipitation = new double[12, 31];
			bool IsDryPreDay = true;
			for (int month = 0; month < 12; month++) {
				for (int day = 0; day < WGen.daysInMonth[month]; day++) {
					DateTime date = new DateTime(2008, month + 1, day + 1);
					Precipitation[month, day] = WGen.GenPcp_Skewed(date, IsDryPreDay);
					if (Precipitation[month, day] > 0.1)
						IsDryPreDay = true;
					else
						IsDryPreDay = false;
				}
			}
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = ".txt";
			dlg.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
			dlg.Title = "选择存储位置";
			if (dlg.ShowDialog() == DialogResult.OK) {
				StreamWriter sw = new StreamWriter(dlg.FileName);
				for (int month = 0; month < 12; month++) {
					sw.Write("month_" + (month + 1) + "：\t");
					for (int day = 0; day < WGen.daysInMonth[month]; day++) {
						sw.Write(Math.Round(Precipitation[month, day], 2) + "\t");
					}
					sw.WriteLine();
				}
				sw.Close();
			}
		}

		private void 一次载入所有气象数据ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			string dir = "D:\\大气所\\刘永和找出的日气象数据\\54923-蒙阴\\";
			WGen.ReadMaxTempData(dir + "DAY54923.TMX");
			WGen.ReadMeanTempData(dir + "DAY54923.TA");
			WGen.ReadRainfallData(dir + "DAY54923.R");
			WGen.ReadRelaHumid(dir + "DAY54923.ua");
			WGen.ReadWindSpeed(dir + "DAY54923.wv");
			WGen.PrepareAllDewPoint();
		}

		private void 抽取各月降雨量ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			List<double>[] result = new List<double>[12];
			for (int i = 0; i < 12; i++) {
				result[i] = new List<double>();
			}
			//将各月降雨量抽取出来
			foreach (int year in WGen.WeatherData.Keys) {
				for (int month = 0; month < 12; month++) {
					for (int day = 0; day < WGen.daysInMonth[month]; day++) {
						if (WGen.WeatherData[year].Precipitation[month, day] > 0)
							result[month].Add(WGen.WeatherData[year].Precipitation[month, day]);
					}
				}
			}
			//保存

			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = ".txt";
			dlg.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
			dlg.Title = "选择存储位置";
			if (dlg.ShowDialog() == DialogResult.OK) {
				StreamWriter sw = new StreamWriter(dlg.FileName);
				for (int month = 0; month < 12; month++) {
					sw.Write("month_" + (month + 1) + "：\t");
					foreach (double value in result[month]) {
						sw.Write(value + "\t");
					}
					sw.WriteLine();
				}
				sw.Close();
			}

		}

		private void 栅格中间结果输出ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MidGridOutDialog dialog = new MidGridOutDialog();
			dialog.ShowDialog();
		}

		private void 计算坡度矩阵ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			GridLayer gridlayer = ((MyTreeNode)this.treeView1.SelectedNode).gridlayer;
			double[,] values = river.CalcSlope();
			for (int i = 0; i < values.GetLength(0); i++) {
				for (int j = 0; j < values.GetLength(1); j++) {
					values[i, j] = Math.Cos(values[i, j]);
				}
			}
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			MyTreeNode node = new MyTreeNode();
			node.bitmap = MatrixFuncs.BitmapFromMatrix(values);
			node.Text = "坡度矩阵";
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = node.bitmap;
			mapViewer1.Display();
		}

		private void 运动波汇流ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			river.demgrid = tempNode.gridlayer;

			int[,] AccumMatrix = river.FlowAccumu_Liu3();
			double[,] matrix2 = river.FlowCalcuOrder();
			//river.SaveCalcuOrder("C:\\Liu.txt");

			MyTreeNode node = new MyTreeNode();
			node.Text = "运动波汇流次序";
			node.bitmap = MatrixFuncs.BitmapFromMatrix5(matrix2);
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = node.bitmap;
			mapViewer1.Display();
		}

		private void 开始模拟刘永和ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Hydro.StormRunoffSim_Horton_Liu();
		}

		private void 一次完成所有计算ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RequestOutForm re = new RequestOutForm();
			if (re.ShowDialog() == DialogResult.OK) {
				this.DEMProcessing(re.row, re.col);
			}
		}
		private void DEMProcessing(int row, int col)
		{
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			//填洼
			river.CheckPit_Planchon(river.m_pDirection, river.demgrid);

			//计算坡向
			double[,] Aspect = river.CalcAspect();
			MatrixFuncs.SaveMatrix(Aspect,"C:/Aspect.txt");
			Bitmap bitmap = MatrixFuncs.BitmapFromMatrix(Aspect);
			MyTreeNode node = new MyTreeNode();
			node.Text = "坡向矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			//计算坡度
			double[,] Slope = river.CalcSlope();
			MatrixFuncs.SaveMatrix(Slope,"C:/Slope.txt");
			bitmap = MatrixFuncs.BitmapFromMatrix(Slope);
			node = new MyTreeNode();
			node.Text = "坡度矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			//计算流向矩阵
			int[,] Direction = river.GridGradientDirection();
			bitmap = MatrixFuncs.BitmapFromMatrix(Direction);
			MatrixFuncs.SaveMatrix(Direction,"C:/FlowDir.txt");
			node = new MyTreeNode();
			node.Text = "流向矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			//计算累积流量矩阵
			int[,] FlowAccum = river.FlowAccumu_Liu3();
			MatrixFuncs.SaveMatrix(FlowAccum,"C:/FlowAccum.txt");
			bitmap = MatrixFuncs.BitmapFromMatrix(FlowAccum);
			node = new MyTreeNode();
			node.Text = "累积流量矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			//生成水系等级
			int[,] Order = river.FlowStrahlerOrder(50);
			MatrixFuncs.SaveMatrix(Order,"C:/StrahlerOrder.txt");
			bitmap = MatrixFuncs.BitmapFromMatrix(Order);
			node = new MyTreeNode();
			node.Text = "水系矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			//运动波汇流等级矩阵
			double[,] CalcOrder = river.FlowCalcuOrder2(row, col);
			bitmap = MatrixFuncs.BitmapFromMatrix5(CalcOrder);
			node = new MyTreeNode();
			node.Text = "流程长度矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);

			bitmap = MatrixFuncs.BitmapFromMatrix5(river.m_pRouteOrd);
			node = new MyTreeNode();
			node.Text = "汇流次序矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);
			//计算滞时演算时间
			river.CalcRouteTime(4000, 3500, 3000, 3000);
			river.FlowCalcuOrder3(row,col);
		}
		private void greenAmpt刘永和ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Hydro.StormRunoffSim_GreenAmpt_Liu();
		}

		private void greenAmptOldToolStripMenuItem_Click(object sender, EventArgs e)
		{
            
		}

		private void 显示WGEN窗ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			WgenForm form = new WgenForm();
			form.ShowDialog();
		}

		private void 移动ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.status = MapStatus.Pan;
			this.mapViewer1.Cursor = Cursors.Hand;
		}

		private void 裁剪ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.status = MapStatus.Clip;
			this.mapViewer1.Cursor = Cursors.Cross;
		}

		private void 矩形ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.status = MapStatus.RectZoom;
			this.mapViewer1.Cursor = Cursors.Cross;
		}

		private void 定点放大ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.status = MapStatus.ZoomIn;
			this.mapViewer1.Cursor = Cursors.SizeAll;
		}

		private void 原图显示ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.CenterX = 0;
			this.mapViewer1.CenterY = 0;
			this.mapViewer1.ZoomValue = 1.0f;
			this.mapViewer1.Display();
		}

		private void 定点缩小ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.status = MapStatus.ZoomOut;
			this.mapViewer1.Cursor = Cursors.SizeAll;
		}

		private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
		{

		}

		private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e)
		{

		}
		
		private double[,] Load_GDAL_Band(Band band)
		{
			double[,] values = new double[band.YSize, band.XSize];
			if (band.DataType == DataType.GDT_Int16) {
				Int16[] data = new short[band.XSize * band.YSize];
				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
				for (int row = 0; row < band.YSize; row++) {
					for (int col = 0; col < band.XSize; col++) {
						values[row, col] = data[row * band.XSize + col];
					}
				}
			} else if (band.DataType == DataType.GDT_Float32) {
				float[] data = new float[band.XSize * band.YSize];
				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
				for (int row = 0; row < band.YSize; row++) {
					for (int col = 0; col < band.XSize; col++) {
						values[row, col] = data[row * band.XSize + col];
					}
				}
			} else if (band.DataType == DataType.GDT_Int32) {
				int[] data = new int[band.XSize * band.YSize];
				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
				for (int row = 0; row < band.YSize; row++) {
					for (int col = 0; col < band.XSize; col++) {
						values[row, col] = data[row * band.XSize + col];
					}
				}
			} else if (band.DataType == DataType.GDT_Float64) {
				double[] data = new double[band.XSize * band.YSize];
				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
				for (int row = 0; row < band.YSize; row++) {
					for (int col = 0; col < band.XSize; col++) {
						values[row, col] = data[row * band.XSize + col];
					}
				}
			} else if (band.DataType == DataType.GDT_Byte) {
				byte[] data = new byte[band.XSize * band.YSize];
				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
				for (int row = 0; row < band.YSize; row++) {
					for (int col = 0; col < band.XSize; col++) {
						values[row, col] = data[row * band.XSize + col];
					}
				}
			} else
			
//				if (band.DataType == DataType.GDT_UInt16) {
//				UInt16[] data = new ushort[band.XSize * band.YSize];
//				band.ReadRaster(0, 0, band.XSize, band.YSize, data, band.XSize, band.YSize, 0, 0);
//				for (int row = 0; row < band.YSize; row++) {
//					for (int col = 0; col < band.XSize; col++) {
//						values[row, col] = data[row * band.XSize + col];
//					}
//				}
//			} else
				throw new Exception("Data Type not known" + band.DataType);
			return values;
		}
		public void SetGeoInfo(GridLayer gridlayer)
		{
			Bitmap bitmap = gridlayer.CreateBitmap6();
			this.panel1.Refresh();
			Graphics g = this.panel1.CreateGraphics();			    
			gridlayer.DrawColorbar(g, 10, 30);
			this.mapViewer1.theBitmap = bitmap;
			this.mapViewer1.ZoomValue = 1.0f / 3;
			LPoint p = gridlayer.CellPosition(gridlayer.rowCount / 2, gridlayer.colCount / 2);
			this.mapViewer1.gridLLX = (float)p.X;
			this.mapViewer1.gridLLY = (float)p.Y;
			this.mapViewer1.gridResolution = (float)gridlayer.resolution;
		}
		MyTreeNode CurrentNode = null;
		private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			CurrentNode = (MyTreeNode)e.Node;
			if (e.Node.Name == "netcdf") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				
				NC_Data2d ncData = (NC_Data2d)node.Tag;
				node.gridlayer.Values = ncData.Data;
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();
				
				return;
			}
			if (e.Node.Name == "hdf") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				
				HDF_Dataset ds = (HDF_Dataset)node.Tag;
				int index = 0;
				if (ds.dimCount == 3)
					index = Convert.ToInt32(node.Text);
				float[,] data0 = ds.ReadData(0, index);
				node.gridlayer.Values = MatrixFuncs.Float2Double(data0);
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();
				return;
			}
			if (e.Node.Name == "hdf5ds") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				
				HDF5_Data2d h5Data = (HDF5_Data2d)node.Tag;
				
				node.gridlayer.Values = h5Data.Data;
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();
				return;
			}
			if (e.Node.Name == "grib1") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				GribFirst.GribMessage message = (GribFirst.GribMessage)node.Tag;
				node.gridlayer.Values = message.PostReadData();
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();    
				return;
			}
			if (e.Node.Name == "grib2") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				Grib2_Decoder.Grib2Message message = (Grib2_Decoder.Grib2Message)node.Tag;
				node.gridlayer.Values = message.PostReadData();
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();   		
				return;
			}
			if (e.Node.Name == "gdal") {
				MyTreeNode node = (MyTreeNode)e.Node;
				if (node.IsLayer == false)
					return;
				
				Band band = (Band)node.Tag;
				node.gridlayer.Values = Load_GDAL_Band(band);				
				SetGeoInfo(node.gridlayer);
				this.mapViewer1.Display();
        		
				return;
			}
//			for (int i = 0; i < treeView1.Nodes.Count; i++) {
//				MyTreeNode node = (MyTreeNode)treeView1.Nodes[i];
//				node.bitmap = null;
//				node.gridlayer = null;
//			}
			MyTreeNode tempNode = (MyTreeNode)e.Node;
			if (tempNode.gridlayer == null) {
				MessageBox.Show("数据为空");
				return;
			}
			SetGeoInfo(tempNode.gridlayer);
//            if(tempNode.bitmap==null && tempNode.gridlayer==null)
//            {
//            	string filename=tempNode.Text;            
//            	GridLayer layer=new GridLayer();
//				layer.ReadNetCDF(filename);
//				Bitmap bitmap= layer.CreateBitmap6();
//				tempNode.gridlayer=layer;
//				this.mapViewer1.theBitmap=bitmap;
//				this.mapViewer1.Display();
//				return;
//            }
            
			if (tempNode.IsLayer == false)
				this.mapViewer1.theBitmap = tempNode.bitmap;
			else
				this.mapViewer1.theBitmap = tempNode.gridlayer.theBitmap;
			this.mapViewer1.Display();
		}

		private void 指示ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.mapViewer1.Cursor = Cursors.Arrow;
			this.mapViewer1.status = MapStatus.Select;
		}

        

		private void mapViewer1_Paint(object sender, PaintEventArgs e)
		{
			this.mapViewer1.Display();
		}

		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{

		}

		private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			treeView1.SelectedNode = e.Node;
			if (e.Node.Text == "Output")
				return;
			CurrentNode = (MyTreeNode)e.Node;
			if (e.Button == MouseButtons.Right) {
				this.contextMenuStrip1.Show(e.X, e.Y + 72);
			}
		}

		private void 栅除ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.treeView1.Nodes.Remove(this.treeView1.SelectedNode);
		}

		private void 流域边界提ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RequestOutForm re = new RequestOutForm();
			if (re.ShowDialog() == DialogResult.OK) {
				int row = re.row;
				int col = re.col;
				MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
				if (tempNode.IsLayer == false)
					tempNode = (MyTreeNode)tempNode.Parent;
				river.demgrid = tempNode.gridlayer;

				double[,] matrix = this.river.FlowCalcuOrder2(row, col);
                
				Bitmap bitmap = MatrixFuncs.BitmapFromMatrix5(matrix);
				MyTreeNode node = new MyTreeNode();
				node.Text = "汇流长度矩阵";
				node.bitmap = bitmap;
				tempNode.Nodes.Add(node);
				mapViewer1.theBitmap = bitmap;
				mapViewer1.Display();
			}
		}

		private void 使用MapObjectsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Assembly assembly = Assembly.LoadFrom(Application.StartupPath + "\\MapObjects_ESSI.dll");
           
			Type type = assembly.GetType("ESSIMO.Form1");
			Form f = (Form)Activator.CreateInstance(type);
			f.ShowDialog();
		}

		private void StatusLabel_Pixel_Click(object sender, EventArgs e)
		{

		}

		private void 栅格图层参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			GridLayerParaDialog dlg = new GridLayerParaDialog();
			dlg.ShowDialog();
		}

		private void 水文气象参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClimateFileSettingsDialog dlg = new ClimateFileSettingsDialog();
			dlg.ShowDialog();
		}

		private void 模型外部率定参数ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			InputParaDialog dlg = new InputParaDialog();
			dlg.ShowDialog();
		}

		private void toolStripDropDownButton1_Click(object sender, EventArgs e)
		{

		}
		private void SetPath(string path)
		{
			HydroSimulate.path = path;
			//设置系统参数的存放目录,在\\SysPara目录下
			string dpath = HydroSimulate.path + "\\SysPara";
			Hydro.m_GridFile = dpath + "\\GridIO.txt";
			Hydro.m_BasinFile = dpath + "\\Basin.txt";
			Hydro.m_ClimateFile = dpath + "\\Climate.txt";
			Hydro.m_RunParaFile = dpath + "\\RunPara.txt";
			Hydro.m_InputParaFile = dpath + "\\InputPara.txt";
			Hydro.m_MuskCoeffFile = dpath + "\\muskingum_coeff.txt";
			Hydro.m_MidOutFile = dpath + "\\MidGridOut.txt";
			Hydro.m_WaterYrTypeFile = dpath + "\\WaterYearType.txt";
		}
		private void OpenDEM(string fileName)
		{
			GridLayer gridlayer = new GridLayer();
			gridlayer.ReadASC(fileName);
			Bitmap bitmap = gridlayer.CreateBitmap5();
			river = new DEMRiverNet(gridlayer);
            
			MyTreeNode node = new MyTreeNode();
			node.IsLayer = true;
			node.gridlayer = gridlayer;
			node.Text = node.gridlayer.FileName;
			this.treeView1.Nodes.Add(node);
			this.treeView1.SelectedNode = node;
			mapViewer1.theBitmap = bitmap;
			this.mapViewer1.Display();
		}
		private void LoadInParaFile()
		{
			Hydro.River = this.river;
			Hydro.LoadSystemParaFile(HydroSimulate.path);
			this.Hydro.ReadInGridLayerData();
			this.Hydro.ReadInClimateData();
		}
		private void hortonLiuTestToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.SetPath("C:\\ESSI_Data-黑河");
			this.OpenDEM("C:\\ESSI_Data-黑河\\YLXDem\\240\\YLXDem240.asc");
			this.DEMProcessing(185, 558);
			this.LoadInParaFile();
			Hydro.StormRunoffSim_Horton_Liu();
		}

		private void greenAmptTestToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.SetPath("C:\\ESSI_Data-黑河");
			this.OpenDEM("C:\\ESSI_Data-黑河\\YLXDem\\240\\YLXDem240.asc");
			this.DEMProcessing(185, 558);
			this.LoadInParaFile();            
			Hydro.StormRunoffSim_GreenAmpt_Liu();
		}

		private void button_2_Color1_Click(object sender, EventArgs e)
		{
			ColorDialog dialog = new ColorDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				button_2_Color1.BackColor = dialog.Color;
			}
		}

		private void button_2_Color2_Click(object sender, EventArgs e)
		{
			ColorDialog dialog = new ColorDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				button_2_Color2.BackColor = dialog.Color;
			}
		}

		private void button_3_Color1_Click(object sender, EventArgs e)
		{
			ColorDialog dialog = new ColorDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				button_3_Color1.BackColor = dialog.Color;
			}
		}

		private void button_3_Color2_Click(object sender, EventArgs e)
		{
			ColorDialog dialog = new ColorDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				button_3_Color2.BackColor = dialog.Color;
			}
		}

		private void button_3_Color3_Click(object sender, EventArgs e)
		{
			ColorDialog dialog = new ColorDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				button_3_Color3.BackColor = dialog.Color;
			}
		}

		private void button6_Click(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode == null)
				return;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			GridLayer gridlayer = tempNode.gridlayer;
			Bitmap bitmap = null;
			if (this.comboBox_ColorSetting.SelectedIndex == 0) {
				bitmap = gridlayer.CreateBitmap();
			} else if (this.comboBox_ColorSetting.SelectedIndex == 1) {
				bitmap = gridlayer.CreateBitmap(this.button_2_Color1.BackColor, this.button_2_Color2.BackColor);
			} else if (this.comboBox_ColorSetting.SelectedIndex == 2) {
				bitmap = gridlayer.CreateBitmap(this.button_3_Color1.BackColor, this.button_3_Color2.BackColor, this.button_3_Color3.BackColor);
			} else if (this.comboBox_ColorSetting.SelectedIndex == 3) {
				bitmap = gridlayer.CreateBitmap5();
			} else if (this.comboBox_ColorSetting.SelectedIndex == 4) {
				bitmap = gridlayer.CreateBitmap6();
			}

			river = new DEMRiverNet(gridlayer);

			MyTreeNode node = new MyTreeNode();
			node.IsLayer = true;
			node.gridlayer = gridlayer;
			node.Text = node.gridlayer.FileName;
			node.bitmap = bitmap;
			this.treeView1.SelectedNode.Nodes.Add(node);
			mapViewer1.theBitmap = bitmap;
			this.mapViewer1.Display();
		}

		private void treeView1_MouseDown(object sender, MouseEventArgs e)
		{

		}

		private void mapViewer1_MouseMove(object sender, MouseEventArgs e)
		{
			if (this.mapViewer1.theBitmap == null)
				return;
			PointF point = this.mapViewer1.ScreenToMap(new PointF(e.X, e.Y));
			int width = this.mapViewer1.theBitmap.Width;
			int height = this.mapViewer1.theBitmap.Height;
			point.X = point.X + width / 2;
			point.Y = point.Y + height / 2;


			if (this.treeView1.SelectedNode == null)
				return;
			MyTreeNode myNode = (MyTreeNode)this.treeView1.SelectedNode;
			GridLayer gridlayer = null;
			if (myNode.IsLayer == true) {
				gridlayer = myNode.gridlayer;
			}
//            else
//            {
//                gridlayer = ((MyTreeNode)myNode.Parent).gridlayer;
//            }
			if (gridlayer == null)
				return;
			int row = (int)(point.Y + 0.5);
			int col = (int)(point.X + 0.5);
			double value = -9999;
			if (row < gridlayer.rowCount && col < gridlayer.colCount && row > 0 && col > 0)
				value = gridlayer.Values[row, col];
			
			string[] strs = GridLayer.ToStr(value);
			string sss = strs[0];
			if (strs.Length == 2)
				sss += "x10^" + strs[1];
			this.StatusLabel_Pixel.Text = " 行:" + row.ToString() + " 列:" + col.ToString() + " 值:" + sss;
			
			double xmin = gridlayer.Extent.xmin;
			double ymin = gridlayer.Extent.ymin;
			double resolution = gridlayer.resolution;
			double X_UTM = xmin + point.X * resolution;
			double Y_UTM = ymin + (height - point.Y) * resolution;
			this.StatusLabel_UTM.Text = "  X=" + X_UTM.ToString("0.000") + " Y=" + Y_UTM.ToString("0.000");

			MapCoord.CenterLongitude(this.Longitude);
			double[] result = MapCoord.ToLonLa_UTM(X_UTM, Y_UTM);
			this.StatusLabel_LonLati.Text = "经E=" + result[0].ToString("0.000") + " 纬N=" + result[1].ToString("0.000");

        
		}

		private void mapViewer1_Load(object sender, EventArgs e)
		{

		}

		private void 设置UTM坐标经度ToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void toolStripTextBox1_TextChanged(object sender, EventArgs e)
		{
			this.Longitude = Convert.ToDouble(TextBox_Longitude.Text);
			if (this.Longitude > 180 || this.Longitude < 0)
				MessageBox.Show("你设的参考经度不在合理的范围之内");
		}

		private void toolStripMenuItem1_Click(object sender, EventArgs e)
		{
			MyTreeNode tempNode = (MyTreeNode)this.treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			river.demgrid = tempNode.gridlayer;
			DateTime t1 = DateTime.Now;
			int[,] matrix = river.FlowAccumu_Liu5();
			double[,] logma = MatrixFuncs.LogTransform(matrix);
			DateTime t2 = DateTime.Now;
			TimeSpan t = t2 - t1;
			this.Text = t.TotalMilliseconds.ToString();
			Bitmap bitmap = MatrixFuncs.BitmapFromMatrix5(logma); //river.CeateRiverSysImage(matrix, 10);
			MyTreeNode node = new MyTreeNode();
			node.Text = "累积流量矩阵";
			node.bitmap = bitmap;
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = bitmap;
			mapViewer1.Display();
		}

		private void 子流域划分ToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RequestOutForm re = new RequestOutForm();
			if (re.ShowDialog() == DialogResult.OK) {
				int row = re.row;
				int col = re.col;
				MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
				if (tempNode.IsLayer == false)
					tempNode = (MyTreeNode)tempNode.Parent;
				river.demgrid = tempNode.gridlayer;

				int[,] matrix = this.river.SubWaterShed(row, col, 2000);
				//Common.SaveMatrix(matrix, "C:\\SubWaterShed.asc");
				Bitmap bitmap = MatrixFuncs.BitmapFromMatrix6(matrix);
				MyTreeNode node = new MyTreeNode();
				node.Text = "子流域";
				node.bitmap = bitmap;
				tempNode.Nodes.Add(node);
				mapViewer1.theBitmap = bitmap;
				mapViewer1.Display();
			}
		}

		private void hortonLinYiTestToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.SetPath("D:\\ESSI_Data");
			this.OpenDEM("D:\\ESSI_Data\\DEM\\240\\Linyi240.asc");
			this.DEMProcessing(671, 432);
			this.LoadInParaFile();
			Hydro.StormRunoffSim_Horton_Liu();
		}

		private void hortonRadarToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.SetPath("D:\\ESSI_Data");
			this.OpenDEM("D:\\ESSI_Data\\DEM\\240\\Linyi240.asc");
			this.DEMProcessing(671, 432);
			this.LoadInParaFile();
			Hydro.StormRunoffSim_Horton_Radar();
		}

        
		void 填洼扫描线ToolStripMenuItemClick(object sender, EventArgs e)
		{
			CUDA_PitFill PitFill = new CUDA_PitFill();
			TimeSpan t1 = DateTime.Now.TimeOfDay;
			double[,] values = PitFill.CheckPit_SweepLine(river.m_pDirection, river.demgrid);
			river.demgrid.Values = values;
			//this.river.demgrid.WriteASC("f:/liu.asc");
			//river.CheckPit_SweepLine(river.m_pDirection, river.demgrid);
			TimeSpan t2 = DateTime.Now.TimeOfDay;
			TimeSpan t3 = t2 - t1;
			this.Text = t3.TotalMilliseconds.ToString();

			//求流向矩阵
			MyTreeNode tempNode = (MyTreeNode)treeView1.SelectedNode;
			if (tempNode.IsLayer == false)
				tempNode = (MyTreeNode)tempNode.Parent;
			MyTreeNode node = new MyTreeNode();
			node.Text = "河道等级矩阵";
			node.bitmap = MatrixFuncs.BitmapFromMatrix6(this.river.demgrid.Values);
			tempNode.Nodes.Add(node);
			mapViewer1.theBitmap = node.bitmap;

			//this.PrepareVector();
			this.mapViewer1.Display();
		}
		void 设置路径ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FolderBrowserDialog dialog = new FolderBrowserDialog();
			if (dialog.ShowDialog() == DialogResult.OK) {
				string[] files = Directory.GetFiles(dialog.SelectedPath);
				foreach (string filename in files) {
					MyTreeNode node = new MyTreeNode();
					node.Text = filename;
					node.IsLayer = true;
					treeView1.Nodes.Add(node);
					
				}
			}
		}
		void TreeView1AfterSelect(object sender, TreeViewEventArgs e)
		{
	
		}
		
		void 另存为文本文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			MyTreeNode node = (MyTreeNode)this.treeView1.SelectedNode;
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = "*.txt";
			dlg.Filter = "Text File(*.txt|*.txt|ASCII码文件(*.asc)|*.asc|All files (*.*)|*.*";
			if (node.IsLayer == true) {			
				if (dlg.ShowDialog() == DialogResult.OK) {
					node.gridlayer.WriteASC(dlg.FileName);
				}
			}
			if (node.IsLayer == false && node.Nodes.Count > 3) {
				if (dlg.ShowDialog() == DialogResult.OK) {
					StreamWriter sw = new StreamWriter(dlg.FileName);
					foreach (MyTreeNode node0 in node.Nodes) {
						sw.Write(node0.Text + "\t");
					}
					sw.Close();
				}
			}
			
		}
		void 关于ToolStripMenuItemClick(object sender, EventArgs e)
		{
			MessageBox.Show("    Developed by Yonghe Liu (刘永和) in " +
			"Henan Polytechnic University(河南理工大学资源环境学院水文系).2016.\n" +
			"    It can be used to browse the gridded data of ASCII or multiple formats" +
			" including NetCDF, HDF4, HDF5, Grib1, Grib2, and GDAL compatible formats (GeoTiff ...)"+
			"The netcdf files with number of dimensions not larger than 4 can be handled." +
			"    This software can also extract drainage networks stably from DEM datasets, " +
			"but I will not provide detailed service for the complete description, since " +
			"now it is a freely used software for public.\n" +
			"    The whole or some part of the software cannot be used for commercial purpose without" +
			" any permission from Dr. Yonghe Liu."
			);
	
		}
		void 添加Grib1文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			if (dialog.ShowDialog() != DialogResult.OK) {
				return;
			}
			GribFirst.GribDecode g = new GribFirst.GribDecode(dialog.FileName);
			List<GribFirst.GribMessage> messages = g.OpenMessages(GribFirst.GribDecode.OpenMode.ScanMessages);
			MyTreeNode node = new MyTreeNode();
			node.Text = dialog.FileName;
			node.Name = "grib1";
			treeView1.Nodes.Add(node);
			for (int i = 0; i < messages.Count; i++) {
				MyTreeNode node2 = new MyTreeNode();
				GridLayer layer = new GridLayer(messages[i].LatiCount, messages[i].LongCount, -9999);
				layer.DownLeft_X=messages[i].Longitudes[0];
				layer.DownLeft_Y=messages[i].Latitudes[messages[i].LatiCount-1];
				layer.resolution=messages[i].Longitudes[1]-messages[i].Longitudes[0];
				node2.gridlayer = layer;
				node2.IsLayer = true;
				node2.Tag = messages[i];
				node2.Text = messages[i].ToString();
				node2.Name = "grib1";
				node.Nodes.Add(node2);
			}
	
		}
		void 添加Grib2文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			if (dialog.ShowDialog() != DialogResult.OK) {
				return;
			}
			Grib2_Decoder.Grib2Decode g = new Grib2_Decoder.Grib2Decode(dialog.FileName);
			List<Grib2_Decoder.Grib2Message> messages = g.OpenMessages(Grib2_Decoder.OpenMode.ScanMessages);
			MyTreeNode node = new MyTreeNode();
			node.Text = dialog.FileName;
			node.Name = "grib2";
			treeView1.Nodes.Add(node);
			for (int i = 0; i < messages.Count; i++) {
				MyTreeNode node2 = new MyTreeNode();
				GridLayer layer = new GridLayer(messages[i].Latitudes.Length, messages[i].Longitudes.Length, -9999);
				layer.DownLeft_X=messages[i].BegtinLongitude;
				layer.DownLeft_Y=messages[i].EndLatitude;
				layer.resolution=messages[i].Longitudes[1]-messages[i].Longitudes[0];
				node2.gridlayer = layer;
				node2.IsLayer = true;
				node2.Tag = messages[i];
				node2.Text = messages[i].ToString();
				node2.Name = "grib2";
				node.Nodes.Add(node2);
			}
	
		}
		void 添加GeoTIFF文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
	
			OpenFileDialog dialog = new OpenFileDialog();
			if (dialog.ShowDialog() != DialogResult.OK) {
				return;
			}
			MyTreeNode node = new MyTreeNode();
			node.Text = dialog.FileName;
			node.Name = "gdal";
			treeView1.Nodes.Add(node);
			
			Gdal.AllRegister();
			Dataset ds =	Gdal.Open(dialog.FileName, Access.GA_ReadOnly);
			int nCount = ds.RasterCount;
			for (int i = 0; i < nCount; i++) {
				Band band = ds.GetRasterBand(i + 1);
				MyTreeNode node2 = new MyTreeNode();
				GridLayer layer = new GridLayer(band.YSize, band.XSize, -9999);
				double[] geotrans = new double[6];
				ds.GetGeoTransform(geotrans);
				layer.resolution = geotrans[1];
				layer.DownLeft_X = geotrans[0];
				layer.DownLeft_Y = geotrans[3] + (band.YSize-1) * geotrans[5];
				
				
				node2.gridlayer = layer;
				node2.IsLayer = true;
				node2.Text = band.GetDescription();
				node2.Name = "gdal";
				node2.Tag = band;
				node.Nodes.Add(node2);		    	
			}
		}
		
		void 添加NetCDF文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			if (dlg.ShowDialog() != DialogResult.OK)
				return;
			
			string filename = dlg.FileName;
			NetCDFDotnet.NCFile ncfile = new NetCDFDotnet.NCFile(filename, NetCDFDotnet.OpenMode.read);
			MyTreeNode node = new MyTreeNode();
			node.Text = dlg.FileName;
			node.Name = "netcdf";
			node.Tag = ncfile;
			treeView1.Nodes.Add(node);
			int varCount = 0;
			//Searching the lat and lon variables
			NCVariable latVar = null;
			foreach (NetCDFDotnet.NCVariable ncvar in ncfile.variables) {
				string varName = ncvar.name.ToLower();
				if (varName.Length > 2 && varName.Substring(0, 3) == "lat") {
					latVar = ncvar;
					break;
				}
			}
			NCVariable lonVar = null;
			foreach (NetCDFDotnet.NCVariable ncvar in ncfile.variables) {
				string varName = ncvar.name.ToLower();
				if (varName.Length > 2 && varName.Substring(0, 3) == "lon") {
					lonVar = ncvar;
					break;
				}
			}
			float[] lons = null;
			float[] lats = null;
			bool needFlip = false;
			double offset = 0;
			double factor = 1;
			
			if (lonVar == null || latVar == null) {
				MessageBox.Show("本软件未检测到经纬度信息，将以资料的原始存储方式读取资料，且不含有坐标信息，" +
				"需您自行处理坐标信息。");
			} else {
			
				if (lonVar.nc_type == NC_Type.NC_FLOAT) {
					lons = lonVar.ValuesFloat;
					lats = latVar.ValuesFloat;
				} else if (lonVar.nc_type == NC_Type.NC_DOUBLE) {
					
					double[] lons2 = lonVar.ValuesDouble;
					double[] lats2 = latVar.ValuesDouble;
					lons = Array.ConvertAll<double,float>(lons2, d => (float)d);
					lats = Array.ConvertAll<double,float>(lats2, d => (float)d);
				} else if (lonVar.nc_type == NC_Type.NC_INT) {
					int[] lons2 = lonVar.ValuesInt32;
					int[] lats2 = latVar.ValuesInt32;
					lons = Array.ConvertAll<int,float>(lons2, d => (float)d);
					lats = Array.ConvertAll<int,float>(lats2, d => (float)d);
				} else
					throw new Exception("数据类型不对");
				
				if (lats[0] < lats[lats.Length - 1]) {
					needFlip = true;
					Array.Reverse(lats);
				}
				if (lonVar.Atributes.ContainsKey("scale_factor")) {
					factor = Convert.ToDouble(lonVar.Atributes["scale_factor"].value);
					offset = Convert.ToDouble(lonVar.Atributes["add_offset"].value);
				}
				//待转换
			}
			
			foreach (NetCDFDotnet.NCVariable ncvar in ncfile.variables) {
				MyTreeNode node2 = new MyTreeNode();
				
				//TreeNode node2= node.Nodes.Add(ncvar.name);
				node2.Name = "netcdf";
				node2.Text = ncvar.name;	
					
				if (ncvar.Dimensions.Length == 4) {
					for (int i = 0; i < ncvar.Dimensions[0].length; i++) {
						MyTreeNode node3 = new MyTreeNode();
						node3.Text = i.ToString();
						node3.Name = "netcdf";
						for (int j = 0; j < ncvar.Dimensions[1].length; j++) {
							int rows = ncvar.Dimensions[2].length;
							int cols = ncvar.Dimensions[3].length;
							MyTreeNode node4 = new MyTreeNode();
							node4.gridlayer = new GridLayer(rows, cols, -9999);
								
							//TreeNode node4=node3.Nodes.Add(j.ToString());
							node4.Name = "netcdf";

							NetCDFDotnet.NC_Data2d ncData = ncfile.GetData2D(ncvar.name, "lon", "lat", i, j);
							ncData.ForDisplay = true;
							if (ncData.XCoord != null && ncData.YCoord != null) {
								node4.gridlayer.DownLeft_X = ncData.CornerX;
								node4.gridlayer.DownLeft_Y = ncData.CornerY;					
								node4.gridlayer.resolution = ncData.resol;
							}
							node4.gridlayer.resolution = ncData.resol;
							node4.Tag = ncData;
							node4.IsLayer = true;
							node4.Text = j.ToString();	
							node3.Nodes.Add(node4);								
						}
						node2.Nodes.Add(node3);
					}
				} else if (ncvar.Dimensions.Length == 3) {
					for (int i = 0; i < ncvar.Dimensions[0].length; i++) {
						MyTreeNode node3 = new MyTreeNode();
							
						//TreeNode node3=node2.Nodes.Add(i.ToString());
						node3.Name = "netcdf";
						int rows = ncvar.Dimensions[1].length;
						int cols = ncvar.Dimensions[2].length;

						NetCDFDotnet.NC_Data2d ncData = ncfile.GetData2D(ncvar.name, "lon", "lat", i, 0);
						ncData.ForDisplay = true;
						node3.gridlayer = new GridLayer(rows, cols, -9999);
						if (ncData.XCoord != null && ncData.YCoord != null) {
							node3.gridlayer.DownLeft_X = ncData.CornerX;							
							node3.gridlayer.DownLeft_Y = ncData.CornerY;
							node3.gridlayer.resolution = ncData.resol;
						}
						
						node3.gridlayer.resolution = ncData.resol;
						node3.Tag = ncData;						
						node3.Text = i.ToString();
						node3.IsLayer = true;
						node2.Nodes.Add(node3);
					}
				} else if (ncvar.Dimensions.Length == 2) {
					int rows = ncvar.Dimensions[0].length;
					int cols = ncvar.Dimensions[1].length;
					
					node2.gridlayer = new GridLayer(rows, cols, -9999);
					NetCDFDotnet.NC_Data2d ncData = ncfile.GetData2D(ncvar.name, "lon", "lat", 0, 0);
					ncData.ForDisplay = true;
					if (ncData.XCoord != null && ncData.YCoord != null) {
						node2.gridlayer.DownLeft_X = ncData.XCoord[0];
						node2.gridlayer.DownLeft_Y = ncData.YCoord[0];					
						node2.gridlayer.resolution = ncData.resol;
					}
					node2.Tag = ncData;
					
					node2.IsLayer = true;						
									
				} else if (ncvar.Dimensions.Length == 1) {
					float[] floatvalues = null;
					int[] intvalues = null;
					short[] shortvalues = null;						
					if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_FLOAT)
						floatvalues = ncvar.ValuesFloat;
					if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_INT)
						intvalues = ncvar.ValuesInt32;
					if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_SHORT)
						shortvalues = ncvar.ValuesInt16;
					int mlength = ncvar.Dimensions[0].length;
					double[] values1d = new double[mlength];
					for (int index = 0; index < mlength; index++) {
						if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_FLOAT) {
							values1d[index] = (double)floatvalues[index];
						} else if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_INT) {
							values1d[index] = (double)intvalues[index];
						} else if (ncvar.nc_type == NetCDFDotnet.NC_Type.NC_SHORT) {
							values1d[index] = (double)shortvalues[index];
						}						
					}
					if (needFlip && ncvar.name.Length > 2 && ncvar.name.ToLower().Substring(0, 3) == "lat") {
						Array.Reverse(values1d);
					}
					for (int index = 0; index < mlength; index++) {
						MyTreeNode node3 = new MyTreeNode();
						node3.Text = values1d[index].ToString("0.0000");
						node2.Nodes.Add(node3);			
					}
				} else if (ncvar.Dimensions.Length > 4) {
					MessageBox.Show("本软件无法支持维度大于4的变量:" + ncvar.name);
				}
				node.Nodes.Add(node2);
				
			}
	
		}
		void 重采样ToolStripMenuItemClick(object sender, EventArgs e)
		{
			ToolForm form = new ToolForm();
			form.grid = this.CurrentNode.gridLayer;
			form.ShowDialog();
			MyTreeNode node = new MyTreeNode();
			node.gridlayer = form.OutGrid;
			node.IsLayer = true;
			node.Text = "Result-" + (treeView1.Nodes[0].Nodes.Count + 1).ToString();
			treeView1.Nodes[0].Nodes.Add(node);
	
		}
		void X3平滑ToolStripMenuItemClick(object sender, EventArgs e)
		{
			double[,] data = MatrixFuncs.Smooth3x3(CurrentNode.gridlayer.Values);
			GridLayer layer = CurrentNode.gridlayer.AttributesCopy();
			layer.Values = data;
			MyTreeNode node = new MyTreeNode();
			node.gridlayer = layer;
			node.IsLayer = true;
			node.Text = "Result-" + (treeView1.Nodes[0].Nodes.Count + 1).ToString();
			treeView1.Nodes[0].Nodes.Add(node);
			
	
		}
		void NetCDF批量处理ToolStripMenuItemClick(object sender, EventArgs e)
		{
			NetCDF_Form form = new NetCDF_Form();
			form.ShowDialog();
	
		}
		void 另存为NetCDF文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			MyTreeNode node = (MyTreeNode)this.treeView1.SelectedNode;
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = "*.nc";
			dlg.Filter = "NetCDF File(*.nc)|*.nc|All files (*.*)|*.*";
			if (node.IsLayer == true) {			
				if (dlg.ShowDialog() == DialogResult.OK) {
					
					node.gridlayer.SaveToNetCDF(dlg.FileName);
				}
			}
	
		}
		void 添加HDF4文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
	
			OpenFileDialog dlg = new OpenFileDialog();
			if (dlg.ShowDialog() != DialogResult.OK)
				return;			
			string filename =dlg.FileName; // "g:/MYD021KM.A2009365.0515.005.hdf";
			HDFDotnet.HDF_File hdffile = new HDF_File(filename);
			MyTreeNode node = new MyTreeNode();
			node.Text = filename;// dlg.FileName;
			node.Name = "hdf";
			node.Tag = hdffile;
			treeView1.Nodes.Add(node);
			
			HDF_Dataset[] datasets = hdffile.Datasets;
			for (int i = 0; i < datasets.Length; i++) {
				HDF_Dataset ds = datasets[i];
				MyTreeNode node2 = new MyTreeNode();
				
				//TreeNode node2= node.Nodes.Add(ncvar.name);
				node2.Name = "hdf";
				node2.Text = ds.Name;	
				int[] dims = ds.dimsizes;
				if (ds.dimCount == 3) {
					for (int index = 0; index < dims[0]; index++) {
						MyTreeNode node3 = new MyTreeNode();
							
						//TreeNode node3=node2.Nodes.Add(i.ToString());
						node3.Name = "hdf";
						int rows = dims[1];
						int cols = dims[2];

						//NetCDFDotnet.NC_Data2d ncData = ncfile.GetData2D(ncvar.name, "lon", "lat", i, 0);
						node3.gridlayer = new GridLayer(rows, cols, -9999);							
						node3.Tag = ds;						
						node3.Text = index.ToString();
						node3.IsLayer = true;
						node2.Nodes.Add(node3);
					}
				} else if (ds.dimCount == 2) {
					int rows = dims[0];
					int cols = dims[1];
					
					node2.gridlayer = new GridLayer(rows, cols, -9999);
					node2.Name = "hdf";
					node2.Tag = ds;		
					node2.IsLayer = true;						
									
				} else if (ds.dimCount == 1) {
					float[] values = ds.ReadData1d();
					for (int index = 0; index < values.Length; index++) {
						MyTreeNode node3 = new MyTreeNode();
						node3.Text = values[index].ToString("0.0000");
						node2.Nodes.Add(node3);			
					}
				}
				node.Nodes.Add(node2);
			}
		}
		void 另存为GeoTiff文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
	        MyTreeNode node = (MyTreeNode)this.treeView1.SelectedNode;
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = "*.tif";
			dlg.Filter = "GeoTIFF File(*.tif)|*.tif|All files (*.*)|*.*";
			if (node.IsLayer == true) {			
				if (dlg.ShowDialog() == DialogResult.OK) {
					node.gridlayer.SaveToGeoTiff(dlg.FileName);
				}
			}
		}
		void 添加HDF5文件ToolStripMenuItemClick(object sender, EventArgs e)
		{
	
			OpenFileDialog dlg = new OpenFileDialog();
			if (dlg.ShowDialog() != DialogResult.OK)
				return;			
			string filename = dlg.FileName; // "g:/MYD021KM.A2009365.0515.005.hdf";
			HDF5.HDF5_File hdffile = new HDF5.HDF5_File(filename);
			MyTreeNode node = new MyTreeNode();
			node.Text = filename;// dlg.FileName;
			node.Name = "hdf5";
			node.Tag = hdffile;
			treeView1.Nodes.Add(node);
			
			AddGroup(node, hdffile.rootGroup);
		}
		void AddGroup(MyTreeNode node, HDF5_Group grp)
		{
			
			for (int i = 0; i < grp.Groups.Length; i++) {
				HDF5_Group grp2 = grp.Groups[i];
				MyTreeNode node2 = new MyTreeNode();
				node2.Text = grp2.Name;
				node2.Name = "hdf5grp";
				node.Nodes.Add(node2);
				AddGroup(node2, grp2);
			}
			for (int i = 0; i < grp.Datasets.Length; i++) {
				HDF5_Dataset ds = grp.Datasets[i];
				MyTreeNode node2 = new MyTreeNode();
				node2.Text = ds.Name;
				node2.Name = "hdf5";
				node2.IsLayer = true;
				node.Nodes.Add(node2);
				AddDatasets(node2, ds);
			}
		}
		void AddDatasets(MyTreeNode node, HDF5_Dataset ds)
		{			
		
			if (ds.ndims == 4) {
				for (int i = 0; i < ds.dims[0]; i++) {
					MyTreeNode node3 = new MyTreeNode();
					node3.Text = i.ToString();
					node3.Name = "hdf5";
					for (int j = 0; j < ds.dims[1]; j++) {
						int rows = (int)ds.dims[2];
						;
						int cols = (int)ds.dims[3];
						MyTreeNode node4 = new MyTreeNode();
						node4.gridlayer = new GridLayer(rows, cols, -9999);
								
						//TreeNode node4=node3.Nodes.Add(j.ToString());
						node4.Name = "hdf5ds";
							
						HDF5_Data2d h5Data = ds.GetData2d(i, j);
						h5Data.ForDisplay = true;
						if (h5Data.XCoord != null && h5Data.YCoord != null) {
							node4.gridlayer.DownLeft_X = h5Data.CornerX;
							node4.gridlayer.DownLeft_Y = h5Data.CornerY;					
							node4.gridlayer.resolution = h5Data.resol;
						}
						node4.gridlayer.resolution = h5Data.resol;
						node4.Tag = h5Data;
						node4.IsLayer = true;
						node4.Text = j.ToString();	
						node3.Nodes.Add(node4);								
					}
					node.Nodes.Add(node3);
				}
			} else if (ds.ndims == 3) {
				for (int j = 0; j < ds.dims[0]; j++) {
					int rows = (int)ds.dims[1];
					int cols = (int)ds.dims[2];
					MyTreeNode node4 = new MyTreeNode();
					node4.gridlayer = new GridLayer(rows, cols, -9999);
								
					//TreeNode node4=node3.Nodes.Add(j.ToString());
					node4.Name = "hdf5ds";

					HDF5_Data2d h5Data = ds.GetData2d(0, j);
					h5Data.ForDisplay = true;
					if (h5Data.XCoord != null && h5Data.YCoord != null) {
						node4.gridlayer.DownLeft_X = h5Data.CornerX;
						node4.gridlayer.DownLeft_Y = h5Data.CornerY;					
						node4.gridlayer.resolution = h5Data.resol;
					}
					node4.gridlayer.resolution = h5Data.resol;
					node4.Tag = h5Data;
					node4.IsLayer = true;
					node4.Text = j.ToString();	
					node.Nodes.Add(node4);								
				}
			} else if (ds.ndims == 2) {
				int rows = (int)ds.dims[0];
				int cols = (int)ds.dims[1];
				//MyTreeNode node4 = new MyTreeNode();
				node.gridlayer = new GridLayer(rows, cols, -9999);
				HDF5_Data2d ncData = ds.GetData2d(0, 0);
				ncData.ForDisplay = true;
				if (ncData.XCoord != null && ncData.YCoord != null) {
					node.gridlayer.DownLeft_X = ncData.XCoord[0];
					node.gridlayer.DownLeft_Y = ncData.YCoord[0];					
					node.gridlayer.resolution = ncData.resol;
				}
				node.Tag = ncData;
				node.Name = "hdf5ds";
				node.IsLayer = true;	
			}
		}
		
	}
}
